<!--
 * @Description: 角色管理
 * @Author: fxg
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-24 11:13:19
-->
<template>
  <div class="pages_content table business">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex;">
        <div class="main_left scroll" style="width: 200px;padding: 20px;">
          <div>
            <el-tree default-expand-all :data="orangeoptions" :props="defaultProps" :expand-on-click-node="false" class="tree-line" :indent="0" @node-click="setTree">
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <div v-if="data.url" style="display: inline-block;width:17px;height:26px;padding:8px 3px 0 0">
                  <img style="width:14px;height:14px" :src="data.url" />
                </div>
                <span>{{ node.label }}</span>
              </span>
            </el-tree>
          </div>
        </div>
        <div class="main_right">
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="display: inline-block;margin-bottom: 10px;">
                  <span style="margin-right: 12px;">名称</span>
                  <el-input v-model="tableParam.name" style="width: 200px;" clearable placeholder="请输入" />
                </span>
                <span style="margin-left: 24px;">
                  <span style="margin-right: 12px;">编码</span>
                  <el-input v-model="tableParam.code" style="width: 200px;" clearable placeholder="请输入" />
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="(tableParam.page = 1), queryPage()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" @click="tableParam.organizationId='',reset()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="add()">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                  添加
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='SHANCHU'))!==-1" size="small" class="bottom_two" @click="batchUpdateOrDelete('update_status', 0)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="batchUpdateOrDelete('update_enable', 1)">
                  <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px;"></i>
                  启用
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="batchUpdateOrDelete('update_enable', 0)">
                  <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px;"></i>
                  禁用
                </el-button>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='FENPYY'))!==-1" size="small" class="botton_five" @click="distributionGet()">分配用户</el-button>
              </div>
              <div>
                <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='BAOCUNPXH'))!==-1" :underline="false" @click="updateSortNum()">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_sort1"></i>
                  </span>
                  保持排序号
                </el-link>
                <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in table" :key="index">
                      <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-link v-if="ButtonList.findIndex(res=>(res.buttonValue=='DAOCHU'))!==-1" :underline="false" @click="$Download(DownloadURL, tableParam)">
                  <span class="el-icon--left">
                    <i class="iconfont iconicon_button_export1"></i>
                  </span>
                  导出
                </el-link>
              </div>
            </div>
            <div class="card_info" :style="style">
              <el-table ref="multipleTable" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection" width="50"></el-table-column>
                <template v-for="(item, index) in table">
                  <el-table-column v-if="item.status" :key="index" :label="item.label" align="center" :width="item.width" :fixed="item.label =='操作'?'right':false">
                    <template slot-scope="scope">
                      <span v-if="scope.row.enable == 0 && item.label == '状态'" style="color:#969799;">禁用</span>
                      <span v-if="scope.row.enable == 1 && item.label == '状态'" style="color:#00A754;">启用</span>
                      <el-button v-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='FENPQX'))!==-1" class="bottom_one" size="mini" @click="showpermiss(scope.row)">分配权限</el-button>
                      <el-button v-if="item.label == '操作'&&ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="update(scope.row)">
                        <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>
                        修改
                      </el-button>
                      <span v-if="item.label !== '操作' && item.label !== '状态'">{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
            <div class="card_bottom">
              <div class="card_bottom_left">
                <div class="top_page_totle">总共{{ total }}条</div>
                <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="queryPage()"></el-pagination>
              </div>
              <div>
                <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="queryPage()">刷新</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="dialogVisible" width="490px" :close-on-click-modal="false" :before-close="resefrom">
      <span slot="title" class="dialog-title">{{ dialogtitle }}</span>
      <div class="dialoginfo dialogVisible">
        <el-form ref="dialogForm" :model="from" :rules="rules" label-width="90px">
          <el-form-item prop="name">
            <template slot="label">
              <span style="color:#FF0000">名称</span>
            </template>
            <el-input v-model="from.name" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <template slot="label">
              <span style="color:#FF0000">编码</span>
            </template>
            <el-input v-model="from.code" placeholder="请输入" @input="changecode"></el-input>
          </el-form-item>
          <el-form-item label="排序号" prop="sortNum">
            <el-input v-model="from.sortNum" type="Number" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="enable">
            <el-radio-group v-model="from.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resefrom()">取 消</el-button>
        <el-button class="bottom_all" @click="save()">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配用户-->
    <el-dialog v-dialogDrag :visible.sync="distribution" width="1072px" :close-on-click-modal="false" :before-close="closedistribution">
      <span slot="title" class="dialog-title">分配用户</span>
      <div class="dialoginfo distribution" style="padding: 0;">
        <div class="dialoginfo-title-bg">
          <div class="dialoginfo-title">
            <div :class="distributionModule == 0 ? 'active' : 'none'" @click="distributionModule = 0">
              <div>
                用户
                <i class="iconfont iconicon_right"></i>
                角色
              </div>
            </div>
            <div :class="distributionModule == 1 ? 'active' : 'none'" @click="distributionModule = 1">
              <div>
                角色
                <i class="iconfont iconicon_right"></i>
                用户
              </div>
            </div>
          </div>
        </div>
        <div v-if="distributionModule == 0" class="dialoginfo-info">
          <div class="dialoginfo-info-div">
            <div class="dialoginfo-info-title">用户</div>
            <div class="dialoginfo-info-info">
              <div v-for="(item, index) in options" :key="index" class="user" @click="chooseop(item, index)">
                <span :class="index == opindex ? 'user-active' : ''">{{ item.name }}</span>
              </div>
            </div>
          </div>
          <div class="dialoginfo-info-center"></div>
          <div class="dialoginfo-info-div">
            <div class="dialoginfo-info-title">已选角色</div>
            <div class="dialoginfo-info-info">
              <el-checkbox-group v-model="optionIds">
                <div v-for="(item, index) in alllist" :key="index" class="user">
                  <el-checkbox :ref="'check'+item.id" :disabled="opindex===null" :label="item.id" @change="alllistFun(item.id,index)">{{ item.name }}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div v-if="distributionModule == 1" class="dialoginfo-info">
          <div class="dialoginfo-info-div">
            <div class="dialoginfo-info-title">角色</div>
            <div class="dialoginfo-info-info">
              <div v-for="(item, index) in alllist" :key="index" class="user" @click="chooseall(item, index)">
                <span :class="index == allindex ? 'user-active' : ''">{{ item.name }}</span>
              </div>
            </div>
          </div>
          <div class="dialoginfo-info-center"></div>
          <div class="dialoginfo-info-div">
            <div class="dialoginfo-info-title">已选用户</div>
            <div class="dialoginfo-info-info">
              <el-checkbox-group v-model="alllistop">
                <div v-for="(item, index) in options" :key="index" class="user">
                  <el-checkbox :ref="'check'+item.id" :disabled="allindex===null" :label="item.id" @change="alllistFun2(item.id,index)">{{ item.name }}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" size="medium" @click="closedistribution()">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog v-dialogDrag :visible.sync="permissshow" width="1072px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">分配权限</span>
      <div class="dialoginfo" style="padding: 0;">
        <div class="right">
          <div class="nav">
            <template v-for="(item, index) in rightList">
              <div :key="index" :class="item.value == rightIndex ? 'right-active' : ''" @click="changetight(item.value)">{{ item.text }}</div>
            </template>
          </div>
          <!-- 功能 -->
          <div v-show="rightIndex !== 5" v-loading="rightloading" class="right-info" element-loading-text="权限同步中...">
            <el-tree ref="functiontree" :key="rightIndex" node-key="nodeId" :default-expand-all="rightIndex == 1?false:true" show-checkbox :data="functiontreeData" :props="defaultProps1" class="tree-line" :indent="0" @check="getButton">
              <span slot-scope="{ node }" class="custom-tree-node">
                <!-- 	<i :style="data.checkstatus ? 'color:red' : ''" :class="data.icon"></i> -->
                <span>{{ node.label }}</span>
              </span>
            </el-tree>
          </div>
          <!-- 数据 -->
          <div v-show="rightIndex == 5" v-loading="rightloading" class="right-info" element-loading-text="数据权限同步中...">
            <div class="right-info-left">
              <el-tree node-key="id" default-expand-all :data="newtree" :props="defaultProps1">
                <span slot-scope="{ node, data }" class="tree-line custom-tree-node">
                  <span v-if="data.hierarchytyp">
                    <i :class="data.icon"></i>
                    <span>{{ node.label }}</span>
                  </span>
                  <el-radio-group v-else v-model="radio" @change="gettable(data)">
                    <el-radio :label="data">
                      <i :class="data.icon"></i>
                      <span :style="shujucheckarr.indexOf(data.id)!==-1?'color:'+bg_color:''">{{ node.label }}</span>
                    </el-radio>
                  </el-radio-group>
                </span>
              </el-tree>
            </div>
            <div class="right-info-right">
              <div style="width: 100%;border:1px solid #e1e5ed;">
                <el-table :data="righttableData" style="width: 100%" height="100%">
                  <el-table-column type="check" :width="righttableData.length==0?'':80">
                    <template slot-scope="scope">
                      <el-checkbox v-model="scope.row.checkStatus" :true-label="1" :false-label="0" @change="SelectionChange(scope.row,scope.row.checkStatus)"></el-checkbox>
                    </template>
                  </el-table-column>
                  <template v-for="(item, index) in tableTitle">
                    <el-table-column :key="index" :prop="item.columnName" :label="item.columnComment" width="auto"></el-table-column>
                  </template>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" class="bottom_all_two" @click="permissshow = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import breaDcrumb from "@/components/breadcrumb";
import { mapGetters } from "vuex";
import {
  queryPage,
  saveOrUpdate,
  batchUpdateOrDelete,
  updateSortNum,
  // getopList,
  rusaveOrUpdate,
  Download,
  userget_Ids
} from "@/api/basedata/role.js";
import { queryPage as queryuserPage } from "@/api/basedata/user";
import { getDicType } from "@/api/common.js";
import { organization as organgequeryPage, get_system_function_buttonByuser as functionTree, } from "@/api/basedata/PersonalRights.js";
import { formatTreeData } from "@/utils/utils";
import { queryPage as queryDataAccessPage } from "@/api/basedata/DataAccess.js";
import { queryPage as querybusinessPage } from "@/api/basedata/business.js";
import {
  saveOrUpdate as savepermissionsOrUpdate,
  queryIds,
  get_table_title,
  query_table_data,
  get_data_limits_table_settings,
  save_or_update,
  get_data_limits_settings,
} from "@/api/basedata/permissions.js";
import styles from "@/app.scss";
import { codeReg, sortReg } from "@/common/RegExp.js";
import { getUserId } from "@/utils/auth.js";
import { Loading } from 'element-ui';
import { getUserInfo } from "@/utils/auth.js";
export default {
  components: {
    breaDcrumb,
  },
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (sortReg(value)) {
        callback();
      } else {
        callback(new Error("请输正整数序号!"));
      }
    };
    return {
      DownloadURL: Download,
      loadingInstance: '',
      rightloading: false,
      tableShow: [],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
        sortNum: [{ required: true, message: "请输入排序号", trigger: "blur" },
        { validator: validatePass1, trigger: "blur", }
        ],
      },
      rightList: [
        {
          text: "功能权限",
          value: 1,
        },
        {
          text: "数据权限",
          value: 5,
        },
        {
          text: '微信小程序权限',
          value: 3
        },
        // {
        //   text: "首页权限",
        //   value: 4,
        // },
        {
          text: "App权限",
          value: 2,
        },
      ],
      rightIndex: 1,
      permissshow: false,

      functiontreeData: [],
      checkkey: [],
      newtree: [],
      tableTitle: [],
      righttableData: [],
      shujucheckarr: [],
      righttable: "",
      bg_color: styles.bg_color,
      alllist: [],
      alllistop: [],
      allindex: null,
      optionIds: [],
      options: [],
      opindex: null,
      /*分配用户*/
      distributionModule: 0,
      /*分配用户弹窗*/
      distribution: false,
      /*添加修改弹窗*/
      dialogVisible: false,
      dialogtitle: "添加",
      /*弹要修改过着添加的数据*/
      from: {
        organizationId: "",
        name: "",
        code: "",
        enable: 1,
        sortNum: "",
        roleEentrance: "entrance_personal",
      },
      /*判断收起展开*/
      showCardNav: true,
      /*搜索关键字段*/
      /*列表展示*/
      table: [
        { label: "编码", width: "auto", prop: "code", status: true },
        { label: "名称", width: "auto", prop: "name", status: true },
        { label: "排序号", width: "auto", prop: "sortNum", status: true },
        { label: "创建人", width: "auto", prop: "createUserName", status: true },
        { label: "状态", width: "auto", prop: "enable", status: true },
        { label: "操作", width: "224px", prop: "", status: true },
      ],
      /*列表选中的数据集*/
      tableParam: {
        page: 1,
        pageSize: 12,
        code: "",
        name: "",
        roleEentrance: "entrance_personal",
        showEnable: 0,
        organizationId: '',
      },
      total: 0,
      ids: [],
      sortIds: [],
      tableData: [],
      orangeoptions: [],
      permissId: "",
      defaultProps: {
        children: "list",
        label: "name",
      },
      defaultProps1: {
        children: "children",
        label: "name",
      },
      radio: '',
      ButtonList: [],
      get_IdsArr: [],//查询的对应角色或者用户
    };
  },
  beforeCreate() {
    /*获取角色列表*/
    getDicType({ code: "role" }).then((res) => {
      this.typeoptions = res.data.items;
    });
    this.orangeoptions = [];
    /*组织树*/
    organgequeryPage().then((res) => {
      if (res.code === 1001) {
        const { data } = res;
        console.log(data)
        this.orangeoptions = data
      }
    });
  },
  mounted() {
    this.ButtonList = this.$ButtonList()
    this.queryPage();
  },
  methods: {
    /**code非中文验证*/
    changecode() {
      this.from.code = codeReg(this.from.code);
    },
    /**分配权限*/
    /**打开弹窗获取权限功能树*/
    async showpermiss(data) {
      this.permissshow = true;
      this.rightloading = true
      this.rightIndex = 1;
      this.permissId = data.id;
      await functionTree({
        type: this.rightIndex,
      }).then((res) => {
        let hash = {};
        const deWeight = (item, cur) => {
          let text = []
          text.push(cur.parentId)
          text.push(cur.id)
          hash[text.join(',')] ? '' : hash[text.join(',')] = true && item.push({ ...cur, nodeId: text.join(',') });
          return item
        }
        let arr = res.data.reduce(deWeight, [])
        this.functiontreeData = formatTreeData(
          arr,
          "id",
          "parentId",
          "children",
          "parent_id"
        );
        console.log(JSON.parse(JSON.stringify(this.functiontreeData)));
      });
      await this.getcheckbutton(data.id);
      this.rightloading = false
    },
    /**权限导航并刷新功能权限树或者数据权限树*/
    async changetight(num) {
      console.log(11);
      this.rightloading = true
      this.functiontreeData = [];
      this.rightIndex = num;
      if (num !== 5) {
        await functionTree({
          type: this.rightIndex,
        }).then((res) => {
          let hash = {};
          const deWeight = (item, cur) => {
            let text = []
            text.push(cur.parentId)
            text.push(cur.id)
            hash[text.join(',')] ? '' : hash[text.join(',')] = true && item.push({ ...cur, nodeId: text.join(',') });
            return item
          }
          let arr = res.data.reduce(deWeight, [])
          console.log(JSON.parse(JSON.stringify(arr)));
          this.functiontreeData = formatTreeData(
            arr,
            "id",
            "parentId",
            "children",
            "parent_id"
          );
          this.getcheckbutton(this.permissId);
        });
        this.rightloading = false
      } else {
        this.radio = ''
        this.righttableData = []
        const params = {
          page: 1,
          pageSize: 10000,
        };
        await querybusinessPage(params).then((res) => {
          res.data.data.forEach((item) => {
            item.children = [];
            item.hierarchytyp = "system";
          });
          this.newtree = res.data.data;
          let arr = [];
          queryDataAccessPage(params).then((res) => {
            arr = res.data.data.map((item) => {
              item.icon = "iconfont icontree_icon_text";
              return item;
            });
            this.newtree.forEach((b) => {
              b.request = 1;
              for (let c in arr) {
                if (b.id == arr[c].systemId) {
                  b.children.push(arr[c]);
                }
              }
            });
            this.getshuju()
          });
        });
        this.rightloading = false

      }
    },
    /**获取数据系统树的数据权限回显*/
    getshuju() {
      get_data_limits_settings({ foreignId: this.permissId, foreignType: "role" }).then(
        (res) => {

          this.shujucheckarr = res.data
        }
      );
    },
    /*获取选中的功能权限*/
    getcheckbutton(foreignId) {
      if (foreignId) {
        let params = {
          foreignType: "role",
          foreignId: foreignId,
          type: this.rightIndex,
        };
        queryIds(params).then((res) => {
          res.data.forEach(res => {
            let arr = []
            arr.push(res.functionId)
            arr.push(res.buttonId)
            res.nodeId = arr.join(',')
          })
          this.checkkey = res.data
          let key = []
          res.data.forEach(item => {
            key.push(item.nodeId)
          })
          this.$nextTick(() => {
            this.$refs.functiontree.setCheckedKeys(key)
          })

        });
      }
    },
    /*每次勾选点击后绑定权限*/
    getButton() {
      let loadingInstance = Loading.service({ text: '授权中...' });
      let keys = this.$refs.functiontree.getCheckedNodes();
      let data = [];
      let newkeys = [];
      newkeys = keys.filter((item) => {
        return !item.children
      });
      if (this.checkkey) {
        let allHasData = this.checkkey.filter((item) =>
          newkeys.some(
            (items) =>
              item.buttonId === items.id && item.functionId == items.parentId
          )
        );
        let deleteData = this.checkkey.filter(
          (item) =>
            !allHasData.some(
              (items) =>
                item.buttonId === items.buttonId &&
                item.functionId == items.functionId
            )
        );
        let addData = newkeys.filter(
          (item) =>
            !allHasData.some(
              (items) =>
                item.id === items.buttonId && item.parentId == items.functionId
            ));
        addData = addData.map((item) => {
          let obj = new Object();
          obj.type = this.rightIndex;
          obj.foreignType = "role";
          obj.foreignId = this.permissId;
          obj.buttonId = item.id;
          obj.buttonName = item.name
          obj.functionId = item.parentId;
          obj.status = 1
          return obj
        });
        deleteData = deleteData.map((item) => {
          let obj = new Object()
          obj.type = this.rightIndex;
          obj.foreignType = "role";
          obj.foreignId = this.permissId;
          obj.buttonId = item.buttonId
          obj.buttonName = item.buttonName
          obj.functionId = item.functionId
          obj.status = 0
          obj.id = item.id
          return obj
        });
        data = [...addData, ...deleteData];
        savepermissionsOrUpdate(data).then(() => {
          this.getcheckbutton(this.permissId);
          loadingInstance.close()
        });
      }
    },




    /*获取数据权限表*/
    async gettable(data) {
      this.loadingInstance = Loading.service({ text: '数据权限拉取中...' });
      this.righttableData = []
      this.righttable = data;
      this.systemId = data.systemId;
      let _this = this
      await get_table_title({ dataLimitsId: data.id }).then((res) => {
        _this.tableTitle = res.data;
      });
      let params = {
        pages: 1,
        pageSize: 99999,
        id: data.id,
        tableName: data.tableName,
      };
      /*获取表回显*/
      let data1 = {
        dataLimitsJoinId: data.id,
        foreignId: _this.permissId,
        foreignType: "role"
      }
      await get_data_limits_table_settings(data1).then(res => {
        _this.tableShow = res.data
      })
      let data2 = {
        dataLimitsJoinId: data.id,
        foreignId: getUserId(),
        foreignType: "user"
      }
      let { data: filter } = await get_data_limits_table_settings(data2)
      let { data: list } = await await query_table_data(params)
      if (getUserInfo().adminStatus == 1) {
        _this.righttableData = list.data
        if (this.loadingInstance) {
          this.loadingInstance.close()
        }
        return
      }
      const deWeight = (item, cur) => {
        if (filter.some(res => (res.dataId == cur.ID))) {
          if (_this.tableShow.some(item1 => (item1.dataId == cur.ID))) {
            cur.checkStatus = 1
          } else {
            cur.checkStatus = 0
          }
          item.push(cur)
        }
        return item
      }
      _this.righttableData = list.data.reduce(deWeight, [])
      if (this.loadingInstance) {
        this.loadingInstance.close()
      }

    },
    /**绑定数据权限*/
    SelectionChange(val, status) {
      this.loadingInstance = Loading.service({ text: '数据授权中...' });
      let arr = []
      if (status == 0) {
        arr = [{
          foreignType: "role",
          foreignId: this.permissId,
          systemId: this.righttable.systemId,
          tableName: this.righttable.tableName,
          dataLimitsId: this.righttable.id,
          dataLimitsDataList: [{
            tableName: this.righttable.tableName,
            status: status,
            id: this.tableShow.find(res => (res.dataId == val.ID)).id,
            dataId: val.ID,
          }]
        }]
      }
      if (status == 1) {
        arr = [{
          foreignType: "role",
          foreignId: this.permissId,
          systemId: this.righttable.systemId,
          tableName: this.righttable.tableName,
          dataLimitsId: this.righttable.id,
          dataLimitsDataList: [{
            tableName: this.righttable.tableName,
            status: status,
            dataId: val.ID,
          }]
        }]
      }
      save_or_update(arr).then(() => {
        this.gettable(this.righttable)
      })

    },


    /**组织树点击时间*/
    setTree(e) {
      console.log(e.id)
      this.tableParam.organizationId = e.id;
      this.reset()
    },
    chooseall(item, index) {
      console.log(JSON.parse(JSON.stringify(this.alllist)))
      this.allindex = index;
      let params = {
        type: "role_to_user",
        sourceId: item.id,
      };
      console.log(1);
      userget_Ids(params).then((res) => {
        this.get_IdsArr = res.data
        this.alllistop = res.data.map((v) => v.targetId)
      });
    },
    chooseop(item, index) {
      console.log(JSON.parse(JSON.stringify(this.options)))
      this.opindex = index;
      let params = {
        type: "user_to_role",
        sourceId: item.id,
      };
      console.log(0);
      userget_Ids(params).then((res) => {
        this.get_IdsArr = res.data
        this.optionIds = res.data.map((v) => v.targetId)
      });
    },
    alllistFun(id) {
      const loading = this.$loading({
        lock: true,
      });
      let arr = [];
      let type = this.$refs[`check${id}`][0].isChecked ? 0 : 1
      if (type === 0) {
        let delid = this.get_IdsArr[this.get_IdsArr.findIndex((v) => v.targetId == id)].id;
        arr.push({ status: 0, id: delid, roleId: id, userId: this.options[this.opindex].id });
      } else {
        arr.push({ status: 1, roleId: id, userId: this.options[this.opindex].id });
      }
      console.log(JSON.parse(JSON.stringify(arr)))
      rusaveOrUpdate(arr).then(() => {
        loading.close();
      });
    },
    alllistFun2(id) {
      const loading = this.$loading({
        lock: true,
      });
      let arr = [];
      let type = this.$refs[`check${id}`][0].isChecked ? 0 : 1
      if (type === 0) {
        let delid = this.get_IdsArr[this.get_IdsArr.findIndex((v) => v.targetId == id)].id;
        arr.push({ status: 0, id: delid, roleId: this.alllist[this.allindex].id, userId: id });
      } else {
        arr.push({ status: 1, roleId: this.alllist[this.allindex].id, userId: id });
      }
      console.log(JSON.parse(JSON.stringify(arr)))
      rusaveOrUpdate(arr).then(() => {
        loading.close();
      });
    },
    closedistribution() {
      this.alllist = [];
      this.alllistop = [];
      this.allindex = null;
      this.optionIds = [];
      this.options = [];
      this.opindex = null;
      this.distribution = false;
    },
    /*获取角色和用户列表*/
    distributionGet() {
      const data = {
        page: 1,
        pageSize: 100000,
      };
      /*角色*/
      queryPage({
        ...data,
        roleEentrance: "entrance_personal",
        enable: 1,
      }).then((res) => {
        this.alllist = res.data.data;
      });
      /*用户*/
      queryuserPage({
        ...data,
        userEentrance: "entrance_personal",
        enable: 1,
      }).then((res) => {
        this.options = res.data.data;
      });
      this.distribution = true;
    },
    /*更新排序号*/
    updateSortNum() {
      updateSortNum(this.sortIds).then(() => {
        this.queryPage();
      });
    },
    /*重置*/
    reset() {
      this.tableParam.code = "";
      this.tableParam.name = "";
      this.queryPage();
    },
    /*删除，禁用，启用，排序*/
    batchUpdateOrDelete(type, status) {
      if (this.ids.length == 0) {
        this.$message({
          message: "请选择要操作的数据项",
          type: "warning",
        });
        return;
      }
      if (type === "update_status") {
        this.$confirm("此操作将永久删除该信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          cancelButtonClass: "bottom_all_two",
          confirmButtonClass: "bottom_all",
          type: "warning",
        })
          .then(() => {
            batchUpdateOrDelete({
              ids: this.ids,
              status: status,
              type: type,
            }).then(() => {
              this.reset();
            });
          })
          .catch(() => { });
      } else {
        batchUpdateOrDelete({
          ids: this.ids,
          status: status,
          type: type,
        }).then(() => {
          this.queryPage();
        });
      }
    },
    /*保存或修改*/
    save() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          saveOrUpdate(this.from).then((res) => {
            if (res.code === 1001) {
              this.resefrom();
              this.queryPage();
              this.$message.success('操作成功')
            }
          });
        }
      });
    },
    resefrom() {
      this.dialogVisible = false;
      this.$refs.dialogForm.resetFields();
    },
    /*获取列表*/
    queryPage() {
      queryPage(this.tableParam).then((res) => {
        this.total = res.data.totalRows;
        this.tableData = res.data.data;
      });
    },
    add() {
      this.dialogtitle = "添加";
      this.$data.from = this.$options.data().from;
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate();
      }, 10);
      this.dialogVisible = true;
    },
    update(data) {
      this.from = data;
      delete this.from.updateTime;
      delete this.from.createTime;
      this.dialogtitle = "修改";
      this.dialogVisible = true;
    },
    /*批量选择*/
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      this.sortIds = [];
      val.forEach((item) => {
        this.ids.push(item.id);
        this.sortIds.push({ id: item.id, sortNum: item.sortNum });
      });
    },
  },
  computed: {
    ...mapGetters({
      screenWidth: "getscreenWidth",
      screenHeight: "getscreenHeight",
      Collapse: "getsCollapse",
    }),
    style() {
      let num = 0;
      if (this.Collapse) {
        num = this.screenWidth - 324;
      } else {
        num = this.screenWidth - 421;
      }
      return "width:" + num + "px;";
    },
  },
};
</script>
<style lang="scss" scoped>
.el-tree {
  display: inline-block;
  width: -webkit-fill-available;
}
.table_link {
  margin: 0 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
.user-active {
  color: $bg_color;
}
.right-info {
  display: flex;
  .right-info-left {
    width: 200px;
    border-right: 1px solid #e1e5ed;
    height: 100%;
    overflow: auto;
    flex: initial;
  }
  .right-info-right {
    flex: 1;
    //background: red;
    height: 100%;
    overflow: auto;
    display: flex;
    justify-content: center;
  }
}
.right {
  height: 600px;
  .nav {
    padding: 0 20px;
    height: 56px;
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    background: #e1e5ed;
    color: #000000;
    > div {
      font-size: 12px;
      font-weight: bold;
      height: 48px;
      width: 18%;
      @include discen;
      cursor: pointer;
    }

    .right-active {
      color: $bg_color;
      border-radius: 8px 8px 0px 0px;
      background: #ffffff;
    }
  }

  .right-info {
    height: calc(100% - 56px);
    padding: 20px;
    overflow: auto;
  }
  .right-info::-webkit-scrollbar {
    width: 3px;
    height: 3px;
  }
  .right-info::-webkit-scrollbar-track {
    background: rgb(239, 239, 239);
    border-radius: 2px;
  }
  .right-info::-webkit-scrollbar-thumb {
    background: #bfbfbf;
    border-radius: 10px;
  }
  .right-info::-webkit-scrollbar-thumb:hover {
    background: #333;
  }
  .right-info::-webkit-scrollbar-corner {
    background: #179a16;
  }
}
.distribution {
  .dialoginfo-info {
    display: flex;
    padding-top: 24px;
    .dialoginfo-info-div {
      width: 496px;
      height: 517px;
      border: 1px solid #e1e5ed;
      overflow: hidden;
    }
    .dialoginfo-info-title {
      padding-left: 20px;
      height: 48px;
      background: #e1e5ed;
      font-size: calc(#{$font_size} + 2px);
      color: #4b4c4d;
      font-weight: bold;
      line-height: 48px;
    }
    .dialoginfo-info-info {
      height: calc(100% - 48px);
      overflow: auto;
      padding: 20px;
      .user {
        line-height: 24px;
        font-size: $font_size;
        color: #4b4c4d;
        font-weight: 400;
      }
      .user:hover {
        cursor: pointer;
      }
    }
    .dialoginfo-info-info::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
    .dialoginfo-info-info::-webkit-scrollbar-track {
      background: rgb(239, 239, 239);
      border-radius: 2px;
    }
    .dialoginfo-info-info::-webkit-scrollbar-thumb {
      background: #bfbfbf;
      border-radius: 10px;
    }
    .dialoginfo-info-info::-webkit-scrollbar-thumb:hover {
      background: #333;
    }
    .dialoginfo-info-info::-webkit-scrollbar-corner {
      background: $bg_color;
    }
    .dialoginfo-info-center {
      width: 40px;
    }
  }
  .dialoginfo-title {
    display: flex;
    align-items: center;
    justify-content: center;
    > div {
      height: 48px;
      width: 190px;
      border: 1px solid $bg_color;
      font-weight: 400;
      font-size: calc(#{$font_size} + 2px);
      @include discen;

      .iconicon_right {
        margin: 0 8px;
      }
    }
    > div:first-child {
      border-radius: 4px 0 0 4px;
    }
    > div:last-child {
      border-radius: 0 4px 4px 0;
    }
    .active {
      background: $bg_color;
      color: #ffffff;
    }
    .none {
      color: $bg_color;
      background: #ffffff;
    }
  }
}

.business {
  .dialogVisible {
    .el-input,
    .el-select {
      width: 320px;
    }
  }
}
</style>
